package com.fz.Contorller;

import com.fz.Mapper.StudentMapper;

import com.fz.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Created by xiao zeng on 2017/7/7.
 */
@Controller
@Transactional

public class StudentContorller {

    @Autowired
    private StudentMapper studao;

    @RequestMapping("index")
    public ModelAndView show(){
        List<Student> ll = studao.query();
        ModelAndView m = new ModelAndView("/WEB-INF/template/index");
        m.addObject("list",ll);
        return m;
    }

    //restful风格接值
    @RequestMapping(value = "delete/{id}",method = RequestMethod.GET)
    public String dele(@PathVariable int id){

        studao.delete(id);

        return "redirect:/index.jsp";//返回到当前控制器的index页面;
    }


    @RequestMapping("add")
    public String add(){
        return "/WEB-INF/template/add";
    }

    @RequestMapping("save")
    public String save(String name ,int score){
        studao.save(name,score);
        return "redirect:/index.jsp";
    }

    @RequestMapping("upload")
    public String upload(@RequestParam("file") CommonsMultipartFile f , HttpServletRequest req) {
           String path = req.getSession().getServletContext().getRealPath("/upload/");
            System.out.println(path);
           File file = new File(path);
           if (!file.exists()){
               file.mkdirs();
           }

           String name = f.getOriginalFilename();
           String ext = name.substring(name.lastIndexOf(".")).toLowerCase();
           String uunaem = UUID.randomUUID().toString()+ext;
            try {
                f.transferTo(new File(path,uunaem));
            } catch (IOException e) {
                e.printStackTrace();
            }

            return "/index";
    }
}
